<?php

class LoginForm extends CFormModel
{
	public $username;
	public $password;

	public function rules()
	{
		return array(
			array('username,password','required'),
			array('password','authenticate'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'username'=>'用户名',
			'password'=>'密码',
		);
	}
	
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())  // we only want to authenticate when no input errors
		{
			$user=User::loadUser($this->username);
			if(!$user){
				$this->addError($this->username,'用户名不存在');	
			}
			elseif($user->password!=$this->password){
				$this->addError($this->password,'密码错误');
			}
			else{
				$identity=new CUserIdentity($this->username, $this->password);
				Yii::app()->user->login($identity);
			}
		}
	}
}

class LoginAction extends CAction
{
	public function run()
	{
		$form=new LoginForm;
		if(isset($_POST['LoginForm'])) {
			$form->attributes=$_POST['LoginForm'];
			if($form->validate()) {            
                $this->controller->redirect(
                    array(
                        'goto', 
                        'id'=>Location::$default,
                    )
                );
			}
		}
		$this->getController()->render('Login',array('form'=>$form));		
	}
}

?>
